package com.fuqi.android.zhongcai.utils;


/**
 * Created by juner on 2014/8/29.
 */

import android.app.Activity;

import com.fuqi.android.zhongcai.application.UniApplication;
import com.fuqi.android.zhongcai.base.ApiUrl;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class FormParamsUtils {


    private static FormParamsUtils fileUpload;
    private static RequestCallback requestCallback;
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    private HashMap<String,String> params;
    private final String upLoadServerUri = ApiUrl.getOrderHandleUrl();
    private int serverResponseCode = 500;
    Runnable networkTask = new Runnable() {

        @Override
        public void run() {
            // TODO
            uploadFile();
        }
    };
    private FormParamsUtils(Activity activity) {
        requestCallback = (RequestCallback) activity;
    }

    public static FormParamsUtils getInstance(Activity activity) {

        if (fileUpload == null) {

            fileUpload = new FormParamsUtils(activity);
        }

        return fileUpload;

    }

    public void request(HashMap<String, String> params) {
        this.params = params;
        new Thread(networkTask).start();

    }

    public int uploadFile() {
        sendStartMsg();
        HttpURLConnection conn = null;
        DataOutputStream dos = null;
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 2 * 1024 * 1024;

            try {

                // open a URL connection to the Servlet
                LogUtils.d("fileInputStream");
                URL url = new URL(upLoadServerUri);
//                LogUtils.d("upLoadServerUri: " + upLoadServerUri + " sourceFileUri: " + localFilePath);
                LogUtils.d("url");
                // Open a HTTP  connection to  the URL
                conn = (HttpURLConnection) url.openConnection();
                conn.setDoInput(true); // Allow Inputs
                conn.setDoOutput(true); // Allow Outputs
                conn.setUseCaches(false); // Don't use a Cached Copy
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Connection", "Keep-Alive");
                conn.setRequestProperty("ENCTYPE", "multipart/form-data");
                conn.setRequestProperty("Charset", "UTF-8");
                conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

                conn.setRequestProperty("TOKEN", UniApplication.getInstance().getUserInfo().getToken());
                dos = new DataOutputStream(conn.getOutputStream());
                dos.writeBytes(twoHyphens + boundary + lineEnd);
                dos.writeBytes(lineEnd);
                LogUtils.d("writeBytes");
                // create a buffer of  maximum size

                LogUtils.d("while");
                // send multipart form data necesssary after file data...
                dos.writeBytes(lineEnd);
                //dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

                StringBuilder sb = new StringBuilder();
                sb.append(twoHyphens + boundary + lineEnd);
                Iterator iter = params.entrySet().iterator();
                while (iter.hasNext()) {
                    Map.Entry entry = (Map.Entry) iter.next();
                    Object key = entry.getKey();
                    Object val = entry.getValue();
                    sb.append("Content-Disposition: form-data; name=\""+ key + "\"" + lineEnd);
                    sb.append(lineEnd);
                    sb.append(val + lineEnd);

                }
                dos.writeBytes(sb.toString());
                serverResponseCode = conn.getResponseCode();
                String serverResponseMessage = conn.getResponseMessage();
                LogUtils.d("serverResponseMessage: " + serverResponseCode);
                LogUtils.i("HTTP Response is : "
                        + serverResponseMessage + ": " + serverResponseMessage);
                if (serverResponseCode != 200) {
                    LogUtils.d("upload error");
                    sendErrorMsg();
                }

                InputStream is = conn.getInputStream();
                InputStreamReader isr = new InputStreamReader(is, "utf-8");
                BufferedReader br = new BufferedReader(isr);
                final String result = br.readLine();
                LogUtils.i(" data-form result:" + result);

//                final AvatarData avatarData = GsonHelper.parseJsonObject(result, AvatarData.class);

                if (serverResponseCode == 200) {
                    LogUtils.i("upload success " + serverResponseCode);
                    sendSuccessMsg();
                }

                //close the streams //
                dos.flush();
                dos.close();

            } catch (MalformedURLException ex) {
                LogUtils.d("MalformedURLException");
                sendErrorMsg();
                ex.printStackTrace();
                LogUtils.i("error: " + ex.getMessage());
            } catch (Exception e) {
                LogUtils.d("Exception: " + e.toString());
                sendErrorMsg();
                e.printStackTrace();
            }

            sendFinishMsg();
            return serverResponseCode;
    }

    private void sendStartMsg() {

        requestCallback.onUploadStart();

    }


    private void sendFinishMsg() {

        requestCallback.onUploadFinish();

    }

    private void sendSuccessMsg() {

        requestCallback.onUploadSuccess();

    }


    private void sendErrorMsg() {

        requestCallback.onUploadError();

    }

    public interface RequestCallback {

        public void onUploadStart();

        public void onUploadFinish();

        public void onUploadSuccess();

        public void onUploadError();

    }

}
